package com.annotation.aop;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

interface Subject {
    void action();
}

class RealSubject implements Subject {
    @Override
    public void action() {
        System.out.println("这是被代理类");
    }
}

class DynomicProxyHandler implements InvocationHandler{

    Object obj;

    /**
     * 返回一个代理传入参数类型的对象
     * @param obj
     * @return
     */
    public Object blind(Object obj) {
        this.obj = obj;
        return Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(), this);
    }

    /**
     * 反射调用方法
     */
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        return method.invoke(obj, args);
    }

    @SuppressWarnings("unchecked")
    public static <T> T proxyHandler(T t) {
        DynomicProxyHandler mih = new DynomicProxyHandler();
        return (T) mih.blind(t);
    }

}

public class DynomicProxy {

    public static void main(String[] args) {
        Subject subject = DynomicProxyHandler.proxyHandler(new RealSubject());
        subject.action();

//        ClothFactory cf = DynomicProxyHandler.proxyHandler(new NikeClothFactory());
//        cf.productCloth();
    }
}

